package bll

import (
	"context"

	"manager/event"
	"manager/model"
	"manager/model/entity"
	"manager/store"
	"manager/store/postgres"
	"time"
)

type faultType struct {
	iFaultType store.IFaultType
}

var FaultType = &faultType{
	iFaultType: postgres.FaultType,
}

func (a *faultType) init() func() {
	return func() {}
}

func (a *faultType) onEvent(*event.Data) {}

// Create 创建
func (a *faultType) Create(ctx context.Context, in *model.FaultTypeCreateRequest) error {
	var (
		err error
	)

	// 构建创建现场数据
	c := buildFaultType(in)
	_, err = a.iFaultType.Create(ctx, c)
	return err
}

// Update 更新
func (a *faultType) Update(ctx context.Context, in *model.FaultTypeUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)

	updateAt := time.Now().Unix()
	in.UpdatedAt = &updateAt

	if in.Name != nil {
		dict["name"] = in.Name
	}

	if in.Desc != nil {
		dict["desc"] = in.Desc
	}

	if in.FaultEnum != nil {
		dict["fault_enum"] = in.FaultEnum
	}

	if in.Level != nil {
		dict["level"] = in.Level
	}

	if in.UpdatedAt != nil {
		dict["updated_at"] = in.UpdatedAt
	}

	// do other update here
	return a.iFaultType.Update(ctx, in.Id, dict)
}

// Delete 删除
func (a *faultType) Delete(ctx context.Context, in *model.FaultTypeDeleteRequest) error {
	return a.iFaultType.Delete(ctx, in.Id)
}

// List 列表查询
func (a *faultType) List(ctx context.Context, in *model.FaultTypeListRequest) (*model.FaultTypeListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.FaultType
		out   = &model.FaultTypeListResponse{}
	)

	if total, list, err = a.iFaultType.List(ctx, in); err != nil {
		return nil, err
	}

	out.Total = total
	out.List = model.FaultTypesEntityToDto(list)

	return out, nil
}

// Find 列表查询
func (a *faultType) Find(ctx context.Context, in *model.FaultTypeInfoRequest) (*model.FaultTypeInfo, error) {
	var (
		err  error
		data *entity.FaultType
		out  = &model.FaultTypeInfo{}
	)

	if data, err = a.iFaultType.Find(ctx, in); err != nil {
		return nil, err
	}

	out = model.FaultTypeEntityToDto(data)
	return out, nil
}

// buildFaultType 构建创建数据现场
func buildFaultType(in *model.FaultTypeCreateRequest) *entity.FaultType {
	// todo: check the entity is required
	return &entity.FaultType{

		Name: in.Name,

		Desc: in.Desc,

		FaultEnum: in.FaultEnum,

		Level: in.Level,

		CreatedAt: time.Now().Unix(),

		UpdatedAt: time.Now().Unix(),
	}
}
